package com.example.emos.api.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.example.emos.api.common.util.PageUtils;
import com.example.emos.api.common.util.QiniuCloudUtil;
import com.example.emos.api.common.util.R;
import com.example.emos.api.controller.form.*;
import com.example.emos.api.db.dao.TbUserDao;
import com.example.emos.api.db.pojo.TbUser;
import com.example.emos.api.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ：Supyo
 * @date ：Created in 2021/11/24 10:54
 * @description：用户花名册模块
 */
@RestController
@RequestMapping("/user")
@Tag(name = "UserController", description = "用户Web接口")
public class UserController {
    @Autowired
    UserService userService;

    @Autowired
    TbUserDao userDao;

    @PostMapping("/login")
    @Operation(summary = "登陆系统")
    public R login(@Valid @RequestBody LoginForm form) {
        HashMap param = JSONUtil.parse(form).toBean(HashMap.class);
        Integer userId = userService.login(param);
        int status = 0;
        R r = R.ok().put("result", userId != null ? true : false);

        //登录成功,生成token，permissions
        if (userId != null) {
            //登录设置，离职用户不能登录
            status = userDao.selectStatus(userId);
            if (status == 4) {
                r = R.error("离职用户不能登录系统！！！");
            }

            //登录成功后返回权限
            Set<String> permissions = userDao.searchUserPermissions(userId);
            StpUtil.setLoginId(userId);
            String token = StpUtil.getTokenInfo().getTokenValue();
            r.put("token", token);
            r.put("permissions", permissions);


        } else if (userId == null) {
            r = R.error("登录失败，请检查账号密码！！！");
        }
        return r;
    }


    @GetMapping("/loadUserInfo")
    @Operation(summary = "登陆成功后加载用户的基本信息")
    @SaCheckLogin
    public R loadUserInfo() {
        int userId = StpUtil.getLoginIdAsInt();
        HashMap summary = userService.searchUserSummary(userId);
        return R.ok(summary);
    }


    @GetMapping("/logout")
    @Operation(summary = "退出系统")
    public R logout() {
        StpUtil.logout();
        return R.ok();
    }


    @PostMapping("/updatePassword")
    @SaCheckLogin
    @Operation(summary = "修改密码")
    public R updatePassword(@Valid @RequestBody UpdatePasswordForm form) {
        int userId = StpUtil.getLoginIdAsInt();
        HashMap param = new HashMap() {{
            put("userId", userId);
            put("password", form.getPassword());
        }};
        int rows = userService.updatePassword(param);
        //修改成功，踢出用户下线
        if (rows > 0) {
            StpUtil.logoutByLoginId(userId);
        }
        return R.ok().put("rows", rows);
    }


    @PostMapping("/searchUserByPage")
    @Operation(summary = "查询用户分页记录")
    public R searchUserByPage(@Valid @RequestBody SearchUserByPageForm form) {
        int page = form.getPage();
        int length = form.getLength();
        int start = (page - 1) * length;
        HashMap param = JSONUtil.parse(form).toBean(HashMap.class);
        param.put("start", start);
        String status = form.getStatus();
        int status1 = 1;
        if (status != null) {
            if (status.equals("初始")) {
                status1 = 1;
            } else if (status.equals("在职(试用期)")) {
                status1 = 2;
            } else if (status.equals("在职(已转正)")) {
                status1 = 3;
            } else if (status.equals("离职")) {
                status1 = 4;
            }
        }
        form.setStatus1(status1);
        System.out.println(status1);
        param.put("status1", status1);
        param.put("roles", form.getRoles());
        System.out.println(form.getRoles());
        PageUtils pageUtils = userService.searchUserByPage(param);
        System.out.println(form.getRoles());
        return R.ok().put("page", pageUtils);
    }


    @PostMapping("/insert")
    @Operation(summary = "添加用户")
    @SaCheckPermission(value = {"ROOT", "HR"}, mode = SaMode.OR)
    public R insert(@Valid @RequestBody InsertUserForm form) {
        TbUser user = JSONUtil.parse(form).toBean(TbUser.class);
        user.setRoles(JSONUtil.parseArray(form.getRoles()).toString());
        user.setCreateTime(new Date());
        int rows = userService.insert(user);
        return R.ok().put("rows", rows);
    }


    @PostMapping("/selectUserById")
    @Operation(summary = "根据Id查询用户")
    public R selectUserById(@Validated @RequestBody SelectUserByIdForm form) {
        TbUser user = userService.selectUserById(form.getId());
        return R.ok().put("list", user);
    }


    @PostMapping("/selectUserById1")
    @Operation(summary = "根据Id查询用户1,然后修改用户资料")
    public R selectUserById1(@Validated @RequestBody SelectUserByIdForm form) {
        HashMap map = userService.selectUserById1(form.getId());
        return R.ok().put("list", map);
    }


    @PostMapping("/update")
    @Operation(summary = "修改用户")
    @SaCheckPermission(value = {"ROOT", "HR"}, mode = SaMode.OR)
    public R update(@Valid @RequestBody UpdateUserForm form) {
        HashMap param = JSONUtil.parse(form).toBean(HashMap.class);
        param.replace("roles", JSONUtil.parseArray(form.getRoles()).toString());
        int rows = userService.update(param);
        if (rows == 1) {
            //修改资料后，把该用户踢下线
            StpUtil.logoutByLoginId(form.getId());
        }
        return R.ok().put("rows", rows);
    }


    @PostMapping("/deleteUserByIds")
    @SaCheckPermission(value = {"ROOT", "HR"}, mode = SaMode.OR)
    @Operation(summary = "删除用户")
    public R deleteUserByIds(@Valid @RequestBody DeleteUserByIdsForm form) {
        Integer userId = StpUtil.getLoginIdAsInt();
        if (ArrayUtil.contains(form.getIds(), userId)) {
            return R.error("您不能删除自己的用户");
        }
        int rows = userService.deleteUserByIds(form.getIds());
        if (rows > 0) {
            //把被删除的用户踢下线
            for (Integer id : form.getIds()) {
                StpUtil.logoutByLoginId(id);
            }
        }
        return R.ok().put("rows", rows);
    }


    @PostMapping("/leave")
    @SaCheckPermission(value = {"ROOT", "HR"}, mode = SaMode.OR)
    @Operation(summary = "离职")
    public R leave(@Valid @RequestBody LeaveForm form) {
        int rows = userService.leave(form.getId());
        return R.ok().put("rows", rows);
    }


    /**
     * 上传头像返回外连接
     */
    @ResponseBody
    @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
    @Operation(summary = "上传头像")
    public R uploadImg(@RequestParam MultipartFile photo, HttpServletRequest request) {
        if (photo.isEmpty()) {
            return R.error("文件为空，请重新上传");
        }
        try {
            byte[] bytes = photo.getBytes();
            String imageName = UUID.randomUUID().toString();
            QiniuCloudUtil qiniuUtil = new QiniuCloudUtil();
            String url1 = "";
            try {
                //使用base64方式上传到七牛云
                String url = qiniuUtil.put64image(bytes, imageName);
                System.out.println(url);
                return R.ok().put("data", url);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return R.ok().put("data", url1);
        } catch (IOException e) {
            return R.error("文件上传发生异常！");
        }
    }


    @GetMapping("/getUsercount")
    @Operation(summary = "首页加载用户数量")
    public R getUsercount() {
        //离职用户数量
        int userLeave = userDao.countUserLeave();
        //用户总数量
        int totalUser = userDao.countTotalUser();
        //当前在职用户
        int user = totalUser - userLeave;

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        // 获取当月第一天
        calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        String firstday = format.format(calendar.getTime());
        // 获取当月最后一天
        calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, 0);
        String lastday = format.format(calendar.getTime());
        //这个月新入职的用户数量
        int monthUser = userDao.countMonthUser(firstday, lastday);


        HashMap data = new HashMap();
        data.put("user", user);
        data.put("monthUser", monthUser);
        data.put("userLeave", userLeave);

        return R.ok().put("data", data);
    }


    @PostMapping("/updateStatusByIds")
    @Operation(summary = "批量修改用户状态")
    @SaCheckPermission(value = {"ROOT", "HR"}, mode = SaMode.OR)
    public R updateStatusByIds(@Valid @RequestBody UpdateStatusByIdsForm form) {
        int[] ids = form.getIds();

        //判断传入的status
        String status = form.getStatus();
        int status1 = 1;
        if (status.equals("初始")) {
            status1 = 1;
        } else if (status.equals("在职(试用期)")) {
            status1 = 2;
        } else if (status.equals("在职(已转正)")) {
            status1 = 3;
        } else if (status.equals("离职")) {
            status1 = 4;
        }

        int rows = 0;
        for (int i = 0; i < ids.length; i++) {
            rows = userService.updateStatusByIds(ids[i], status1);
            rows += rows;
        }
        return R.ok().put("rows", rows);
    }
}
